package com.yc.demo.d1011.qq;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class QQServer {

    public static void main(String[] args) throws IOException {
        // 建立连接服务端, 监听 8888 端口
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("开始监听 8888");
        // 开始监听, 客户端连接成功, 返回 Socket对象
        // 连接成功前, 处于阻塞状态
        Socket socket = serverSocket.accept();
        InetAddress inetAddress = socket.getInetAddress();
        System.out.println("地址: "+inetAddress.getHostAddress());
        // 获取输入输出流
        InputStream in = socket.getInputStream();
        OutputStream out = socket.getOutputStream();
        Scanner scanner = new Scanner(System.in);
        new Thread(()->{
            boolean running = true;
            while(running){
                byte[] bytes = new byte[1024];
                int count;
                try {
                    count = in.read(bytes);
                    String msg = new String(bytes,0,count);
                    System.out.println("收到客户器的消息: "+msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
        ).start();
        new Thread(()->{
            boolean running = true;
            while(running){
                System.out.print("我说: ");
                String msg = scanner.nextLine();
                try {
                    out.write(msg.getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        // 主线程应该在此等待, 再关闭 socket
        // socket.close();

    }

}
